package com.water.camera.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.water.camera.activity.BatchPreviewAct;
import com.water.camera.activity.PinAct;
import com.water.camera.bean.MediaData;
import com.water.camera.databinding.ItemAlbum2Binding;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PinImgAdapter extends RecyclerView.Adapter {

    final ArrayList<MediaData> list = new ArrayList<>();
    PinAct act;
    boolean show = true;

    public PinImgAdapter(PinAct act) {
        this.act = act;
    }

    public void showSelect(boolean bo) {
        show = bo;
        notifyItemRangeChanged(0, getItemCount());
    }

    public void append(ArrayList<MediaData> tmp) {
        int p = list.size();
        list.addAll(tmp);
        notifyItemRangeInserted(p, tmp.size());
    }

    public void insert(int p, List<MediaData> tmp) {
        list.remove(p);
        notifyItemRemoved(p);
        list.addAll(p, tmp);
        notifyItemRangeInserted(p, tmp.size());
    }

    public void remove(int p) {
        list.remove(p);
        notifyItemRemoved(p);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemAlbum2Binding binding = ItemAlbum2Binding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ImgHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ImgHolder) {
            ((ImgHolder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class ImgHolder extends RecyclerView.ViewHolder {
        ItemAlbum2Binding binding;

        public ImgHolder(ItemAlbum2Binding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            binding.frame.setRatio(1.33f);
            MediaData item = list.get(p);
            Glide.with(itemView).load(new File(item.getPath())).into(binding.ivCover);
            binding.ivSelect.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
            binding.ivSelect.setOnClickListener(v -> {
                Intent i = new Intent(itemView.getContext(), BatchPreviewAct.class);
                i.putExtra("path", item.getPath());
                i.putExtra("from", 1);
                itemView.getContext().startActivity(i);
            });
            itemView.setOnClickListener(v -> {
                act.editPic(getBindingAdapterPosition(), item);
            });
        }
    }
}
